/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
public:
    ListNode* swapPairs(ListNode* head) {
        if(head == nullptr || head->next == nullptr) // 递归法
            return head;
        ListNode* tmp = swapPairs(head->next->next); // 把两个结点之外的看成另一部分
        head->next->next = head;
        auto ret = head->next; // 保存一下要返回的结点
        head->next = tmp;
        return ret;

        /*if(head == nullptr || head->next == nullptr) // 迭代法
            return head;
        // newHead -> 1 -> 2 -> 3
        ListNode *newHead = new ListNode(0);
        // 1和2换 -> cur和next1换
        // prev -> cur -> next1 -> next2
        // cur -> prev -> next1 -> next2
        ListNode *prev=newHead, *cur=head, *next1=head->next, *next2=next1->next;
        while(cur && next1)
        {
            prev->next = next1;
            next1->next = cur;
            cur->next = next2;

            prev = cur;
            cur = next2;
            if(cur)
                next1 = cur->next;
            if(next1)
                next2 = next1->next;
        }
        return newHead->next;*/
    }
};